package com.atguigu.gulimall.ware.service.impl;

import com.atguigu.gulimall.common.constant.WareConstant;
import com.atguigu.gulimall.ware.entity.PurchaseDetailEntity;
import com.atguigu.gulimall.ware.service.PurchaseDetailService;
import com.atguigu.gulimall.ware.service.WareSkuService;
import com.atguigu.gulimall.ware.vo.MergeVo;
import com.atguigu.gulimall.ware.vo.PurchaseDoneVo;
import com.atguigu.gulimall.ware.vo.PurchaseItemDoneVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.gulimall.common.utils.PageUtils;
import com.atguigu.gulimall.common.utils.Query;

import com.atguigu.gulimall.ware.dao.PurchaseDao;
import com.atguigu.gulimall.ware.entity.PurchaseEntity;
import com.atguigu.gulimall.ware.service.PurchaseService;
import org.springframework.transaction.annotation.Transactional;


@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {

    @Autowired
    private PurchaseDetailService purchaseDetailService;

    @Autowired
    private WareSkuService wareSkuService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPageUnreceive(Map<String, Object> params) {
        QueryWrapper<PurchaseEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("status", 0).or().eq("status", 1);
        IPage<PurchaseEntity> page = this.page(new Query<PurchaseEntity>().getPage(params),wrapper
        );

        return new PageUtils(page);
    }


    @Transactional
    @Override
    public void mergePurchase(MergeVo mergeVo) {
        Long purchaseId = mergeVo.getPurchaseId();
        if (purchaseId == null){    // 没有选合并到的采购单， 这时候生成一个
            PurchaseEntity purchaseEntity = new PurchaseEntity();
            purchaseEntity.setUpdateTime(new Date());
            purchaseEntity.setCreateTime(new Date());
            purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.CREATED.getCode());
            this.save(purchaseEntity);
            purchaseId = purchaseEntity.getId();
        }

        // 修改采购单详情，也就是各个采购项， 也就是选中的采购需求， 修改状态，由新建状态改为已分配状态， 并修改分配的采购单ID
        List<Long> itemList = mergeVo.getItems();
        Long finalPurchaseId = purchaseId;
        List<PurchaseDetailEntity> updateDetailList = itemList.stream().map(item -> {
            PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
            purchaseDetailEntity.setId(item);
            purchaseDetailEntity.setPurchaseId(finalPurchaseId);
            purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.ASSIGNED.getCode());
            return purchaseDetailEntity;

        }).collect(Collectors.toList());
        purchaseDetailService.updateBatchById(updateDetailList);

        // 更新采购单 时间
        PurchaseEntity purchase = new PurchaseEntity();
        purchase.setId(purchaseId);
        purchase.setUpdateTime(new Date());
        this.updateById(purchase);


    }

    @Override
    public void receivePurchase(List<Long> ids) {
        // 1 采购单
        // 1.1 确认采购单是新建状态或者是已分配状态（不能是已经领取或者已经完成）
        // 1.2 更新采购单状态为已领取状态
        List<PurchaseEntity> purchaseList = ids.stream().map(id -> {
            PurchaseEntity purchase = this.getById(id);
            return purchase;
        }).filter(item -> {
            return item.getStatus() == WareConstant.PurchaseStatusEnum.CREATED.getCode() || item.getStatus() == WareConstant.PurchaseStatusEnum.ASSIGNED.getCode();
        }).map(item -> {
            item.setStatus(WareConstant.PurchaseStatusEnum.RECEIVED.getCode());
            item.setUpdateTime(new Date());
            return item;
        }).collect(Collectors.toList());
        this.updateBatchById(purchaseList);

        // 2.采购项，也就是采购需求
        purchaseList.forEach(item -> {
            Long purchaseId = item.getId();
            List<PurchaseDetailEntity> detailEntityList = purchaseDetailService.listPurchaseDetailByPurchaseId(purchaseId);
            List<PurchaseDetailEntity> updateList = detailEntityList.stream().map(detail -> {
                PurchaseDetailEntity detailEntity = new PurchaseDetailEntity();
                detailEntity.setId(detail.getId());
                detailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.BUYING.getCode());
                return detailEntity;
            }).collect(Collectors.toList());
            purchaseDetailService.updateBatchById(updateList);
        });
    }

    @Transactional
    @Override
    public void purchaseDone(PurchaseDoneVo doneVo) {
        // 采购单状态
        // 采购项，也就是采购需求状态
        // 成功采购更新入库

        boolean flag = true; // 采购单状态 所有采购项都正常才正常
        List<PurchaseItemDoneVo> itemList = doneVo.getItems();
        List<PurchaseDetailEntity> updateDetailList = new ArrayList<>();
        for (PurchaseItemDoneVo itemDoneVo : itemList) {
            Integer status = itemDoneVo.getStatus();
            PurchaseDetailEntity detailEntity = new PurchaseDetailEntity();
            detailEntity.setId(itemDoneVo.getItemId());
            detailEntity.setStatus(status);
            if (status == WareConstant.PurchaseDetailStatusEnum.HASERROR.getCode()){ // 采购需求采购有异常
                flag = false;
            }else {
                PurchaseDetailEntity detail = purchaseDetailService.getById(itemDoneVo.getItemId());
                Long skuId = detail.getSkuId();
                Integer skuNum = detail.getSkuNum();
                Long wareId = detail.getWareId();
                // 采购完成的话需要增加库存
                wareSkuService.addStock(skuId, wareId, skuNum);
            }
            updateDetailList.add(detailEntity);
        }
        purchaseDetailService.updateBatchById(updateDetailList);

        // 采购单状态修改
        PurchaseEntity entity = new PurchaseEntity();
        entity.setId(doneVo.getId());
        entity.setUpdateTime(new Date());
        entity.setStatus(flag?WareConstant.PurchaseStatusEnum.FINISHED.getCode(): WareConstant.PurchaseStatusEnum.HASERROR.getCode());
        this.updateById(entity);

    }

}